package com.bckj.fastboot.iot.biz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bckj.fastboot.core.extra.cache.CacheOps;
import com.bckj.fastboot.core.lang.model.PageResult;
import com.bckj.fastboot.core.page.PageSupport;
import com.bckj.fastboot.iot.biz.repository.IotProtocolItemRepository;
import com.bckj.fastboot.iot.biz.repository.IotProtocolRepository;
import com.bckj.fastboot.iot.common.constant.IotCacheConstants;
import com.bckj.fastboot.iot.common.dto.query.IotProtocolQuery;
import com.bckj.fastboot.iot.common.dto.response.IotProtocolResponse;
import com.bckj.fastboot.iot.common.entity.IotProtocolItem;
import com.bckj.fastboot.iot.biz.service.IotProtocolQueryService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * IotProtocolQueryServiceImpl
 *
 * @author wfc
 **/
@Service
public class IotProtocolQueryServiceImpl implements IotProtocolQueryService  {
    @Resource
    private IotProtocolRepository iotProtocolRepository;
    @Resource
    private IotProtocolItemRepository iotProtocolItemRepository;
    @Resource
    private CacheOps cacheOps;

    @Override
    public IotProtocolResponse details(Long id) {
        return iotProtocolRepository.getBaseMapper().findById(id);
    }

    @Override
    public List<IotProtocolResponse> findList(IotProtocolQuery query) {
        return iotProtocolRepository.getBaseMapper().findList(query);
    }

    @Override
    public PageResult<IotProtocolResponse> page(IPage<IotProtocolResponse> page, IotProtocolQuery query) {
        var result = PageSupport.page(page, query, this::findList);
        return PageResult.of(result);
    }

    @Override
    public List<IotProtocolItem> findItems(String protocolCode, String cmd) {
        Assert.notNull(protocolCode, "protocolCode can not be null");
        boolean hasCmd = StringUtils.hasText(cmd);
        String key = protocolCode + (hasCmd ? cmd : "");
        var cache = cacheOps.redisCache(IotCacheConstants.IOT_PROTOCOL_ITEM_CACHE);
        return cacheOps.runCaching(cache,
                () -> iotProtocolItemRepository.lambdaQuery()
                        .eq(IotProtocolItem::getProtocolCode, protocolCode)
                        .eq(hasCmd, IotProtocolItem::getCmd, cmd)
                        .list(), key
        );
    }
}
